package com.classtest.DemoExpend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.classtest.DemoExpend.bean.DbUser;
import com.classtest.DemoExpend.service.DbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PersonalController {

    @Autowired
    DbUserService dbUserService;

    // 获取个人信息
    @RequestMapping("/personalInfo")
    public String personalInfo(HttpServletRequest request, DbUser dbUser) {
        DbUser user = (DbUser) request.getSession().getAttribute("user");
        dbUser.setUserFName(user.getUserFName());
        List<DbUser> userPersonalInfo = dbUserService.getPersonalInfo(JSON.toJSONString(dbUser));
        Map<String,Object> personalInfo = new HashMap<>();
        List<Object> list = new ArrayList<>();
        for (DbUser personal: userPersonalInfo){
            Map<String,Object> res = new HashMap<>();
            res.put("id",personal.getId());
            res.put("userTName",personal.getUserTName());
            res.put("type",personal.getType());
            res.put("idCardType",personal.getIdCardType());
            res.put("idCard",personal.getIdCard());
            res.put("birthday",personal.getBirthday());
            res.put("address",personal.getAddress());
            res.put("userMail",personal.getUserMail());
            res.put("userFName",personal.getUserFName());
            list.add(res);
        }
        personalInfo.put("personal",list);
        return JSON.toJSONString(personalInfo);
    }

    // 修改个人信息
    @RequestMapping("/updatePersonalInfo")
    public String updatePersonalInfo(@RequestBody String json, HttpSession session) {
        Map<String,Object> updatePersonal = new HashMap<>();
        try {
            DbUser user = (DbUser)session.getAttribute("user");
            if(user != null){
                DbUser user1 = JSONObject.parseObject(json,DbUser.class);
                user1.setId(user.getId());
                dbUserService.updatePersonalInfo(JSON.toJSONString(user1));
                updatePersonal.put("flag","ok");
            }else {
                updatePersonal.put("flag","error");
                updatePersonal.put("resMsg","还没有登录");
            }


        } catch (Exception e) {
            updatePersonal.put("error",e.toString());
        }
        return JSON.toJSONString(updatePersonal);
    }
}
